/**
 * Copyright (c) 2009 Jim Hurne
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */
package org.tzconverter.tzgroup;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.awt.event.ContainerAdapter;
import java.awt.event.ContainerEvent;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdesktop.layout.GroupLayout;
import org.tzconverter.gui.GradientButton;
import org.tzconverter.tzdisplay.TimeZoneDisplayPanel;
import org.tzconverter.tzdisplay.TimeZoneDisplayView;
import org.tzconverter.util.Icons;

/**
 * Swing implementation of the TimeZoneGroupView.
 * 
 * @since May 16, 2009
 */
public class TimeZoneGroupPanel extends JPanel implements TimeZoneGroupView
{
  private static final long serialVersionUID = -6682431070458972391L;
  
  private final Log logger = LogFactory.getLog(this.getClass());  
 
  private JLabel errorLabel;
  private JLabel addLabel;
  private JTextField timeZoneIdField;
  private JButton addButton;
  
  private JPanel addPanel;
  private JPanel displayPane;  
  
  private final Icons icons;
  
  public TimeZoneGroupPanel(Icons icons)
  {
    this.icons = icons;
    
    this.setOpaque(false);
    
    createComponents();
    layoutComponents();
  }
  
  private void createComponents()
  {
    errorLabel = new JLabel(" ");
    errorLabel.setIcon(icons.getError());
    errorLabel.setForeground(Color.RED);
    errorLabel.setVisible(false);
        
    timeZoneIdField = new JTextField(15);
    timeZoneIdField.setMaximumSize(timeZoneIdField.getPreferredSize());
    //timeZoneIdField.setColumns(15);
    timeZoneIdField.getDocument().addDocumentListener(new DocumentListener() {
      public void changedUpdate(DocumentEvent event)
      {
        //Do nothing
      }

      public void insertUpdate(DocumentEvent event)
      {
        Document doc = event.getDocument();
        try
        {
          firePropertyChange(PROP_TIME_ZONE_ID, null, doc.getText(0, doc.getLength()));
        }
        catch (BadLocationException e)
        {
          throw new RuntimeException(e.getMessage(), e);
        }       
      }

      public void removeUpdate(DocumentEvent event)
      {
        Document doc = event.getDocument();
        try
        {
          firePropertyChange(PROP_TIME_ZONE_ID, null, doc.getText(0, doc.getLength()));
        }
        catch (BadLocationException e)
        {
          throw new RuntimeException(e.getMessage(), e);
        }               
      }      
    });
    
    addLabel = new JLabel("Add Time Zone:");
    addLabel.setLabelFor(timeZoneIdField);
    addLabel.setForeground(Color.WHITE);
    addLabel.setVisible(true);
    
    addButton = new GradientButton("Add");
    addButton.setIcon(icons.getApply());
    
    addPanel = new JPanel();
    addPanel.setOpaque(false);
    
    displayPane = new JPanel();
    //Get the TimeZoneDisplayPanel preferred size.
    Dimension singlePanelSize = new TimeZoneDisplayPanel(icons).getPreferredSize();
    //Make enough initial room for five display panels
    Dimension preferredSize = new Dimension(singlePanelSize.width, singlePanelSize.height * 5);            
    displayPane.setMinimumSize(preferredSize);  
    displayPane.setOpaque(false);
  }
  
  private void layoutComponents()
  {
    //Layout hte displayPane
    //Show the time zone display panels vertically
    displayPane.setLayout(new BoxLayout(displayPane, BoxLayout.PAGE_AXIS));
    
    //Show the tzDisplayPane in a JScrollPane
    JScrollPane scrollPane = new JScrollPane(displayPane, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    scrollPane.setOpaque(false);
    scrollPane.getViewport().setOpaque(false);
    //scrollPane.setViewportBorder(BorderFactory.createLoweredBevelBorder());
    calcMinSize(scrollPane);
    
    //Layout the addPanel
    GroupLayout layout = new GroupLayout(addPanel);
    addPanel.setLayout(layout);
    
    layout.setAutocreateGaps(true);
    layout.setHonorsVisibility(true);
    
    layout.setHorizontalGroup(
        layout.createParallelGroup()
          .add(errorLabel)
          .add(addLabel)
          .add(
              layout.createSequentialGroup()
                .add(timeZoneIdField)
                .add(addButton)
              )
        );
    
    layout.setVerticalGroup(
        layout.createSequentialGroup()
          .add(errorLabel)
          .add(addLabel)
          .add(
              layout.createParallelGroup(GroupLayout.BASELINE)
                .add(timeZoneIdField)
                .add(addButton)
              )
        );
    
    // Layout this panel
    // We use GroupLayout because it is one of the few layout managers
    // that respects the minimumSizes of components.
    GroupLayout thisLayout = new GroupLayout(this);
    this.setLayout(thisLayout);
    
    thisLayout.setHorizontalGroup(
        thisLayout.createSequentialGroup()
        .add(scrollPane)
       );
    thisLayout.setVerticalGroup(
        thisLayout.createParallelGroup()
        .add(scrollPane)
      );
  }
  
  /**
   * Getter that provides access to the "Add" Panel.  This allows
   * the user of this component to layout the add panel anyway they
   * see fit.
   * 
   * @return
   */
  public JPanel getAddPanel()
  {
    return addPanel;
  }

  /**
   * Calculates the minimum size for the given JScrollPane.
   * 
   * @param scrollPane
   */  /**
   * Calculates the minimum size for the given JScrollPane.
   * 
   * @param scrollPane
   */
  private void calcMinSize(JScrollPane scrollPane)
  {
    logger.debug("Vertical scroll bar size: " + scrollPane.getVerticalScrollBar().getPreferredSize());    
    //Calculate the scroll pane's minimum size
    Dimension minSize = displayPane.getMinimumSize();
    Dimension vertBar = scrollPane.getVerticalScrollBar().getPreferredSize();
    
    int vbWidth = 0;
    if(scrollPane.getViewportBorder() != null)
    {
      Insets inner = scrollPane.getViewportBorder().getBorderInsets(scrollPane.getViewport());
      logger.debug("Viewport border insets: " + inner);
      vbWidth += inner.left + inner.right;
    }
    Insets outer = scrollPane.getInsets();
    logger.debug("Outer insets: " + outer);
    vbWidth += outer.right + outer.left;
    
    Dimension prefSize = new Dimension(minSize.width + vertBar.width + vbWidth, minSize.height + 30);
    logger.debug("Calculated preferred size: " + prefSize);
    
    scrollPane.setMinimumSize(prefSize);
  }
  
  /* (non-Javadoc)
   * @see org.tzconverter.addtz.AddTimeZoneView#showError(java.lang.String)
   */
  public void showError(String message)
  {
    errorLabel.setVisible(true);
    errorLabel.setText(message);
    addLabel.setVisible(false);
  }

  /* (non-Javadoc)
   * @see org.tzconverter.addtz.AddTimeZoneView#clearError()
   */
  public void clearError()
  {
    errorLabel.setVisible(false);
    errorLabel.setText(" ");
    addLabel.setVisible(true);
  }

  /* (non-Javadoc)
   * @see org.tzconverter.addtz.AddTimeZoneView#getTimeZoneId()
   */
  public String getTimeZoneId()
  {
    return timeZoneIdField.getText();
  }

  /* (non-Javadoc)
   * @see org.tzconverter.addtz.AddTimeZoneView#setTimeZoneId(java.lang.String)
   */
  public void setTimeZoneId(String id)
  {
    timeZoneIdField.setText(id);
  }

  /* (non-Javadoc)
   * @see org.tzconverter.addtz.AddTimeZoneView#isAddButtonEnabled()
   */
  public boolean isAddButtonEnabled()
  {
    return addButton.isEnabled();
  }

  /* (non-Javadoc)
   * @see org.tzconverter.addtz.AddTimeZoneView#setAddButtonEnabled(boolean)
   */
  public void setAddButtonEnabled(boolean enabled)
  {
    addButton.setEnabled(enabled);
  }

  /* (non-Javadoc)
   * @see org.tzconverter.addtz.AddTimeZoneView#addActionListener(java.awt.event.ActionListener)
   */
  public void addActionListener(ActionListener listener)
  {
    addButton.addActionListener(listener);
  }

  /* (non-Javadoc)
   * @see org.tzconverter.addtz.AddTimeZoneView#removeActionListener(java.awt.event.ActionListener)
   */
  public void removeActionListener(ActionListener listener)
  {
    addButton.removeActionListener(listener);
  }
  

  /* (non-Javadoc)
   * @see org.tzconverter.addtz.AddTimeZoneView#addTimeZoneDisplay(org.tzconverter.tzdisplay.TimeZoneDisplayView)
   */
  public void addTimeZoneDisplay(TimeZoneDisplayView tzDisplayView)
  {
    //Only add the timeZoneDisplay view if it is actually a GUI component
    //And we have a container to add it to
    if(tzDisplayView instanceof Component 
        && displayPane != null)
    {
      displayPane.add((Component) tzDisplayView);
      ((JComponent) displayPane).revalidate();
      displayPane.repaint();
    }
  }

  @Override
  public void addTimeZoneRemoveListener(TimeZoneRemoveListener listener)
  {
    ContainerListenerAdapter adapter = new ContainerListenerAdapter(listener);
    displayPane.addContainerListener(adapter);
  }

  @Override
  public void removeTimeZoneRemoveListener(TimeZoneRemoveListener listener)
  {
    ContainerListenerAdapter adapter = new ContainerListenerAdapter(listener);
    displayPane.removeContainerListener(adapter);
  }
  
  /**
   * An adapter that converts a TimeZoneRemovedListener into
   * a ContainerListener that only responds to remove events.
   * 
   */
  private static class ContainerListenerAdapter extends ContainerAdapter
  {
    private final TimeZoneRemoveListener listener;
    
    public ContainerListenerAdapter(TimeZoneRemoveListener listener)
    {
      this.listener = listener;
    }

    @Override
    public void componentRemoved(ContainerEvent event)
    {
      Component removed = event.getChild();
      if(removed instanceof TimeZoneDisplayView)
      {
        listener.timeZoneRemoved((TimeZoneDisplayView) removed);
      }
    }

    /** Returns true if the reference to the wrapped listener is the same
     * as the object tested against. 
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj)
    {
      if(obj instanceof ContainerListenerAdapter)
      {
        ContainerListenerAdapter adapter = (ContainerListenerAdapter) obj;
        return adapter.listener == this.listener;
      }
      return false;
    }   
  }
}
